package com.huo.filestransport.service;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.huo.common.enumtype.FileTypeEnum;
import com.huo.common.enumtype.FtpFileStatusEnum;
import com.huo.common.enumtype.R;
import com.huo.filestransport.dao.FtpFileInfoDao;
import com.huo.filestransport.dao.FtpfilelogDao;
import com.huo.filestransport.entity.FtpFileInfoEntity;
import com.huo.filestransport.entity.Ftpfilelog;
import com.huo.filestransport.vo.FtpFileInfo;
import com.huo.filestransport.vo.FtpFileSimpleInfo;
import com.huo.filestransport.vo.FtpServerInfo;
import com.huo.util.DateUtils;
import com.huo.util.ListUtil;
import com.huo.util.SftpUtil;
import org.apache.commons.net.ftp.FTPFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jcraft.jsch.ChannelSftp;



@Service
public class SftpService {
	
	@Autowired
	private SftpUtil sftpUtil;
	
	@Autowired
	private FtpFileInfoDao ftpFileInfoDao;
	
	@Autowired
	private FtpfilelogDao ftpfilelogDao;
	
	@Autowired
	private FtpServerInfo ftpServerInfo;
	
	private final static Logger logger = LoggerFactory.getLogger(SftpService.class);
	
	/**
	   * 对检测功能初始化
	 */
	public void clearFtpFileInfo() {
		//删除信息
		logger.info("清理 t_ftpfileinfo表开始");
		ftpFileInfoDao.truncateTable();
		logger.info("清理 t_ftpfileinfo表结束");
		
	}
	
	
	
	/**
	 * 检测ftp文件是否在变动
	 * 状态      0 服务器正在处理 1服务器已处理完，可以下载 2 已下载完成 
	 */
	public R checkFtpFile(String ftpDirectory) {
		//获取指定目录下的文件列表
		logger.info("检测ftp文件是否在变动，获取指定目录下的文件列表：" + ftpDirectory);
		List<String> fileFtpPathList = new ArrayList<String>();
		List<FtpFileInfo> ftpFileList = new ArrayList<FtpFileInfo>();
		ChannelSftp ftp = null;
		try {
			ftp = sftpUtil.getFTPConnection();
			R r = sftpUtil.readFTPFileDirectory(ftpDirectory,fileFtpPathList,ftp,ftpFileList);
			if(!R.checkOK(r)) {
				return r;
			}
			for(FtpFileInfo ffi : ftpFileList) {
				FTPFile ftpFile = ffi.getFtpFile();
				//根据ftpfilepath 去获取信息
				FtpFileInfoEntity ftpFileInfoEntity = ftpFileInfoDao.selectByFtpFilePath(ffi.getFtpPath());
				long ftpfiledatetime = ftpFile.getTimestamp().getTimeInMillis();
				int rawOffset = 0;
				long ftpfiledatetimeTotal = ftpfiledatetime + rawOffset;
				//若不存在，进行保存，状态未0
				if(ftpFileInfoEntity == null) {
					logger.info("首次检测到的文件：" + ffi.getFtpPath());
					FtpFileInfoEntity record = new FtpFileInfoEntity();
					record.setCreatetime(new Date());
					record.setFtpfiledatetime(String.valueOf(ftpfiledatetimeTotal));
					record.setFtpfilename(ftpFile.getName());
					record.setFtpfilepath(ffi.getFtpPath());
					record.setFtpfilesize(ftpFile.getSize());
					record.setUpdatetime(record.getCreatetime());
					record.setFtpfilestatus(FtpFileStatusEnum.FTPFILE_STATUS_HANDLE.getCode());
					ftpFileInfoDao.insert(record);
				}else {
					if(FtpFileStatusEnum.FTPFILE_STATUS_HANDLE.getCode().equals(ftpFileInfoEntity.getFtpfilestatus())) {
						//若存在比较名称 大小  时间，若一致，修改状态为1，不一致，不修改
						if(ftpFile.getSize() == ftpFileInfoEntity.getFtpfilesize() 
								&& ftpFile.getName().equals(ftpFileInfoEntity.getFtpfilename())
								&& String.valueOf(ftpFile.getTimestamp().getTimeInMillis()).equals(ftpFileInfoEntity.getFtpfiledatetime())) {
							FtpFileInfoEntity record = new FtpFileInfoEntity();
							record.setId(ftpFileInfoEntity.getId());
							record.setUpdatetime(new Date());
							record.setFtpfilestatus(FtpFileStatusEnum.FTPFILE_STATUS_DOWNLOAD.getCode());
							ftpFileInfoDao.updateByPrimaryKeySelective(record);
							logger.info("可下载的文件：" + ffi.getFtpPath());
						}else {
							FtpFileInfoEntity record = new FtpFileInfoEntity();
							record.setId(ftpFileInfoEntity.getId());
							record.setUpdatetime(new Date());
							record.setFtpfiledatetime(String.valueOf(ftpfiledatetimeTotal));
							record.setFtpfilesize(ftpFile.getSize());
							ftpFileInfoDao.updateByPrimaryKeySelective(record);
							logger.info("服务器正在处理的文件：" + ffi.getFtpPath());
							
						}
					}
				}
			}
		}catch (Exception e) {
			logger.error(e.getMessage(),e);	
			logger.error("检测ftp文件是否在变动，获取指定目录下的文件列表失败" + ftpDirectory);
			return R.error("检测ftp文件是否在变动，获取指定目录下的文件列表失败" + ftpDirectory+ e.getMessage());
		}finally {
			sftpUtil.closeSFTPConnection(ftp);
			logger.info("检测ftp文件是否在变动，获取指定目录下的文件列表结束：" + ftpDirectory);
		}
		return R.ok();
		
	}
	
	
	public R checkFtpFileByDB() {
		logger.info("检测配置文件中的FPT文件是否在变动 开始");
		ChannelSftp ftp = null;
		List<FtpFileInfoEntity> ftpFileInfoEntityList = ftpFileInfoDao.selectByFtpFileStatus(FtpFileStatusEnum.FTPFILE_STATUS_HANDLE.getCode());
		try {
			if(ftpFileInfoEntityList.size() > 0) {
				ftp = sftpUtil.getFTPConnection();
			}
			for(FtpFileInfoEntity ftpFileInfoEntity : ftpFileInfoEntityList) {
				R r = sftpUtil.getFtpFileInfo(ftpFileInfoEntity.getFtpfilepath(), ftp);
				if(R.checkOK(r)) {
					FTPFile ftpFile = (FTPFile) r.get("obj");
					if(ftpFile.getSize() == ftpFileInfoEntity.getFtpfilesize() 
							&& ftpFile.getName().equals(ftpFileInfoEntity.getFtpfilename())
							&& String.valueOf(ftpFile.getTimestamp().getTimeInMillis()).equals(ftpFileInfoEntity.getFtpfiledatetime())) {
						FtpFileInfoEntity record = new FtpFileInfoEntity();
						record.setId(ftpFileInfoEntity.getId());
						record.setUpdatetime(new Date());
						record.setFtpfilestatus(FtpFileStatusEnum.FTPFILE_STATUS_DOWNLOAD.getCode());
						ftpFileInfoDao.updateByPrimaryKeySelective(record);
						logger.info("可下载的文件：" + ftpFileInfoEntity.getFtpfilepath());
					}else {
						FtpFileInfoEntity record = new FtpFileInfoEntity();
						record.setId(ftpFileInfoEntity.getId());
						record.setUpdatetime(new Date());
						long ftpfiledatetime = ftpFile.getTimestamp().getTimeInMillis();
						int rawOffset = 0;
						long ftpfiledatetimeTotal = ftpfiledatetime + rawOffset;
						record.setFtpfiledatetime(String.valueOf(ftpfiledatetimeTotal));
						record.setFtpfilesize(ftpFile.getSize());
						ftpFileInfoDao.updateByPrimaryKeySelective(record);
						logger.info("服务器正在处理的文件：" + ftpFileInfoEntity.getFtpfilepath());
						
					}
				}
			}
			logger.info("检测配置文件中的FPT文件是否在变动 结束");
			return R.ok();
		} catch (Exception e) {
			logger.info("检测配置文件中的FPT文件是否在变动 异常");
			logger.error(e.getMessage(),e);
			return R.error();
		}
		

	}
	
	
	
	/**
	   * 下载指定目录下的文件
	   * 未检测服务器文件是否正在处理 
	 * @param ftpPath
	 * @param localPath
	 */
	public R downloadFtpFileByFtpDirectory(String ftpDirectory, String localPath) {
		logger.info("下载指定目录下的文件开始：" + ftpDirectory);
		List<String> fileDirectoryList = new ArrayList<String>();
		List<FtpFileInfo> ftpFileList = new ArrayList<FtpFileInfo>();
		ChannelSftp ftp = null;
		try {
			ftp = sftpUtil.getFTPConnection();
			R r = sftpUtil.readFTPFileDirectory(ftpDirectory,fileDirectoryList,ftp,ftpFileList);
			if(!R.checkOK(r)) {
				return r;
			}
			for(FtpFileInfo ftpFileInfo : ftpFileList) {
				FTPFile ftpFile = ftpFileInfo.getFtpFile();
				Date beginTime = new Date();
				R re = sftpUtil.downloadFtpFileByFtpPath(ftpFileInfo.getFtpPath(),localPath,ftp);
				if(!R.checkOK(re)) {
					continue;
				}
				Ftpfilelog ftpfilelogRecord = new Ftpfilelog();
				ftpfilelogRecord.setBegintime(beginTime);
				ftpfilelogRecord.setEndtime(new Date());
				long ftpfiledatetime = ftpFile.getTimestamp().getTimeInMillis();
				int rawOffset = 0;
				ftpfilelogRecord.setFtpfiledatetime(String.valueOf(ftpfiledatetime+rawOffset));
				ftpfilelogRecord.setFtpfilename(ftpFile.getName());
				ftpfilelogRecord.setFtpfilepath(ftpFileInfo.getFtpPath());
				ftpfilelogRecord.setFtpfilesize(ftpFile.getSize());
				ftpfilelogRecord.setFtplocalpath(localPath + ftpFileInfo.getFtpPath());
				ftpfilelogRecord.setFtpfiletype(FileTypeEnum.DOWNLOAD.getCode());
				ftpfilelogDao.insert(ftpfilelogRecord);
			}
			return R.ok();
		} catch (Exception e) {
			logger.error(e.getMessage(),e);	
			return R.error("下载指定目录的文件失败" + ftpDirectory);
		}finally {
			sftpUtil.closeSFTPConnection(ftp);
			logger.info("下载指定目录下的文件结束：" + ftpDirectory);
		}
	}
	
	/**
	 * 上传指定目录的文件
	 * @param ftpDirectory
	 * @param localDirectory
	 * @return
	 */
	/*public R uploadFileByLocalDirectory(String ftpDirectory, String localDirectory) {
		logger.info("上传指定目录下的文件开始 -> ftpDirectory:" + ftpDirectory + " localDirectory:"+localDirectory);
		ChannelSftp ftp = null;
		List<String> localfilePathList = new ArrayList<String>();
		List<File> localFileInfoList = new ArrayList<File>();
		try {
			ftp = sftpUtil.getUpFTPConnection();
			R r = sftpUtil.readLocalFileByDirectory(localDirectory, localfilePathList,localFileInfoList);
			if(!R.checkOK(r)) {
				return r;
			}
			for(File localFile : localFileInfoList) { 
				//取出中间的目录
				String reallyFtpDirectory  = ftpDirectory + makeSubDirecotry(localFile.getPath(),localDirectory,localFile.getName());
				Date beginTime = new Date();
				R uploadRe = sftpUtil.uploadFile(reallyFtpDirectory, localFile.getPath(), ftp);
				if(!R.checkOK(uploadRe)) {
					continue;
				}
				Ftpfilelog ftpfilelogRecord = new Ftpfilelog();
				ftpfilelogRecord.setBegintime(beginTime);
				ftpfilelogRecord.setEndtime(new Date());
				ftpfilelogRecord.setFtpfiledatetime(String.valueOf(localFile.lastModified()));
				ftpfilelogRecord.setFtpfilename(localFile.getName());
				ftpfilelogRecord.setFtpfilepath(ftpDirectory);
				ftpfilelogRecord.setFtpfilesize(localFile.length());
				ftpfilelogRecord.setFtplocalpath(localFile.getPath());
				ftpfilelogRecord.setFtpfiletype(FileTypeEnum.UPLOAD.getCode());
				ftpfilelogDao.insert(ftpfilelogRecord);
			}
			logger.info("上传指定目录下的文件结束 ,上传文件个数:"+ localFileInfoList.size());
			return r;
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			return R.error();
		} finally {
			sftpUtil.closeSFTPConnection(ftp);
		}
		
	}*/
	
	/**
	 * 获取指定目录下的文件列表
	 * @param ftpDirectory
	 * @return
	 */
	public List<FtpFileSimpleInfo> readFTPFileDirectory(String ftpDirectory){
		logger.info("获取指定目录下的文件列表开始：" + ftpDirectory);
		List<String> fileDirectoryList = new ArrayList<String>();
		List<FtpFileInfo> ftpFileList = new ArrayList<FtpFileInfo>();
		List<FtpFileSimpleInfo> returnFtpFileList = new ArrayList<FtpFileSimpleInfo>();
		ChannelSftp ftp = null;
		try {
			ftp = sftpUtil.getFTPConnection();
			R r = sftpUtil.readFTPFileDirectory(ftpDirectory,fileDirectoryList,ftp,ftpFileList);
			if(!R.checkOK(r)) {
				return null;
			}
			for(FtpFileInfo ftpFileInfo : ftpFileList) {
				FTPFile ftpFile = ftpFileInfo.getFtpFile();
				FtpFileSimpleInfo ffsi = new FtpFileSimpleInfo();
				ffsi.setFtpFilename(ftpFile.getName());
				ffsi.setFtpFilePath(ftpFileInfo.getFtpPath());
				ffsi.setFtpFileSize(String.valueOf(ftpFile.getSize()));
				long ftpfiledatetime = ftpFile.getTimestamp().getTimeInMillis();
				int rawOffset = 0;
				ffsi.setFtpFileCreateDate(DateUtils.longToDate(ftpfiledatetime+rawOffset));
				returnFtpFileList.add(ffsi);
			}
			
		}catch (Exception e) {
			logger.error(e.getMessage(),e);	
			return returnFtpFileList;
		}
		finally {
			sftpUtil.closeSFTPConnection(ftp);
		}
		logger.info("获取指定目录下的文件列表结束：" + ftpDirectory);
		return returnFtpFileList;
	}
	
	
	
	
	/**
	   * 下载指定DB中的文件
	   * 检测服务器文件是否正在处理 
	 * @param ftpPath
	 * @param localPath
	 */
	public R downloadFtpFileByDB() {
		String localPath = ftpServerInfo.getLocalDirectory();
		logger.info("下载指定目录(DB)下的文件开始：" );
		ChannelSftp ftp = null;
		try {
			ftp = sftpUtil.getFTPConnection();
			//对数据库进行查询，查询状态为1的数据
			List<FtpFileInfoEntity> ftpFileInfoEntityList = ftpFileInfoDao.selectByFtpFileStatus(FtpFileStatusEnum.FTPFILE_STATUS_DOWNLOAD.getCode());
			if(ftpFileInfoEntityList != null && ftpFileInfoEntityList.size() > 0) {
				ftp = sftpUtil.getFTPConnection();
			}
			for(FtpFileInfoEntity ffie : ftpFileInfoEntityList) {
				Date beginTime = new Date();
				R r = sftpUtil.downloadFtpFileByFtpPath(ffie.getFtpfilepath(),localPath,ftp);
				if(R.checkOK(r)) {
					//修改记录，将状态改为2
					FtpFileInfoEntity record = new FtpFileInfoEntity();
					record.setId(ffie.getId());
					record.setUpdatetime(new Date());
					record.setFtpfilestatus(FtpFileStatusEnum.FTPFILE_STATUS_FISH.getCode());
					ftpFileInfoDao.updateByPrimaryKeySelective(record);
					//记录日志
					Ftpfilelog ftpfilelogRecord = new Ftpfilelog();
					ftpfilelogRecord.setBegintime(beginTime);
					ftpfilelogRecord.setEndtime(new Date());
					ftpfilelogRecord.setFtpfiledatetime(ffie.getFtpfiledatetime());
					ftpfilelogRecord.setFtpfilename(ffie.getFtpfilename());
					ftpfilelogRecord.setFtpfilepath(ffie.getFtpfilepath());
					ftpfilelogRecord.setFtpfilesize(ffie.getFtpfilesize());
					ftpfilelogRecord.setFtplocalpath(localPath + ffie.getFtpfilepath());
					ftpfilelogRecord.setFtpfiletype(FileTypeEnum.DOWNLOAD.getCode());
					ftpfilelogDao.insert(ftpfilelogRecord);
				}
			}
			logger.info("下载指定目录(DB)下的文件结束："  + "下载的文件数量为：" + ftpFileInfoEntityList.size());
			return R.ok();
		} catch (Exception e) {
			logger.error(e.getMessage(),e);	
			return R.error("下载指定目录(DB)的文件失败" );
		}finally {
			sftpUtil.closeSFTPConnection(ftp);
		}
	}
	
	/**
	 * 上传DB中的文件
	 * ftpdownloadDirectory 为本地下载的ftp的目录，方便分目录的上传
	 * @return
	 */
	/*public R uploadFileByDB(String ftpUploadDirectory,String localDirectory,String ftpdownloadDirectory) {
		logger.info("上传DB中的文件开始 -> ftpUploadDirectory:{},localDirectory:{}" ,ftpUploadDirectory,localDirectory );
		ChannelSftp ftp = null;
		try {
			
			List<FtpFileInfoEntity> ftpFileInfoEntityList = ftpFileInfoDao.selectByFtpFileStatus(FtpFileStatusEnum.FTPFILE_STATUS_FISH.getCode());
			if(ftpFileInfoEntityList != null && ftpFileInfoEntityList.size() > 0) {
				ftp = sftpUtil.getUpFTPConnection();
			}
			for(FtpFileInfoEntity ffe : ftpFileInfoEntityList) {
				String localPath = localDirectory+ffe.getFtpfilepath();
				File localFile = new File(localPath);
				Date beginTime = null;
				if(localFile.isFile()) {
					String reallyFtpDirectory = ftpUploadDirectory + makeSubDirecotry(localPath,localDirectory+ftpdownloadDirectory,localFile.getName());
					beginTime = new Date();
					R uploadRe = sftpUtil.uploadFile(reallyFtpDirectory,localPath, ftp);
					if(!R.checkOK(uploadRe)) {
						continue;
					}
				}
				FtpFileInfoEntity record = new FtpFileInfoEntity();
				record.setId(ffe.getId());
				record.setUpdatetime(new Date());
				record.setFtpfilestatus(FtpFileStatusEnum.FTPFIEL_STATUS_UPLOAD.getCode());
				ftpFileInfoDao.updateByPrimaryKeySelective(record);
				
				Ftpfilelog ftpfilelogRecord = new Ftpfilelog();
				ftpfilelogRecord.setBegintime(beginTime);
				ftpfilelogRecord.setEndtime(new Date());
				ftpfilelogRecord.setFtpfiledatetime(String.valueOf(ffe.getFtpfiledatetime()));
				ftpfilelogRecord.setFtpfilename(localFile.getName());
				ftpfilelogRecord.setFtpfilepath(ffe.getFtpfilepath());
				ftpfilelogRecord.setFtpfilesize(localFile.length());
				ftpfilelogRecord.setFtplocalpath(localFile.getPath());
				ftpfilelogRecord.setFtpfiletype(FileTypeEnum.UPLOAD.getCode());
				ftpfilelogDao.insert(ftpfilelogRecord);
			}
			logger.info("上传DB中的文件结束 ,上传文件个数:"+ ftpFileInfoEntityList.size());
			return R.ok();
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			return R.error();
		} finally {
			sftpUtil.closeSFTPConnection(ftp);
		}
		
	}*/
	
	/**
	   * 下载指定的文件
	 * @param ftpPath
	 * @param localPath
	 */
	public R downloadFtpFielByFtpPath(String ftpPath, String localPath) {
		logger.info("下载指定的文件开始：" + ftpPath);
		ChannelSftp ftp = null;
		try {
			ftp = sftpUtil.getFTPConnection();
			Date beginTime = new Date();
			R r = sftpUtil.downloadFtpFileByFtpPath(ftpPath,localPath,ftp);
			if(!R.checkOK(r)) {
				return r;
			}
			FTPFile ftpfile = (FTPFile) r.get("obj");
			Ftpfilelog ftpfilelogRecord = new Ftpfilelog();
			ftpfilelogRecord.setBegintime(beginTime);
			ftpfilelogRecord.setEndtime(new Date());
			long ftpfiledatetime = ftpfile.getTimestamp().getTimeInMillis();
			int rawOffset = 0;
			long ftpfiledatetimeTotal = ftpfiledatetime + rawOffset;
			ftpfilelogRecord.setFtpfiledatetime(String.valueOf(ftpfiledatetimeTotal));
			ftpfilelogRecord.setFtpfilename(ftpfile.getName());
			ftpfilelogRecord.setFtpfilepath(ftpPath);
			ftpfilelogRecord.setFtpfilesize(ftpfile.getSize());
			ftpfilelogRecord.setFtplocalpath(localPath + ftpPath);
			ftpfilelogRecord.setFtpfiletype(FileTypeEnum.DOWNLOAD.getCode());
			ftpfilelogDao.insert(ftpfilelogRecord);
			return r;
		} catch (Exception e) {
			logger.error(e.getMessage(),e);	
			return R.error("下载指定的文件失败" + ftpPath);
		}finally {
			sftpUtil.closeSFTPConnection(ftp);
			logger.info("下载指定的文件结束：" + ftpPath);
		}
	}
	
	/**
	 * 保存自定义的文件，准备下载
	 * @param DefinitionFtpFilePathList
	 * @return
	 */
	public R saveDefinitionFileInfo(List<String> DefinitionFtpFilePathList) {
		logger.info("保存优先下载的文件开始");
		try {
			for(String definitionFtpPath : DefinitionFtpFilePathList ) {
				FtpFileInfoEntity ftpFileInfoEntity = ftpFileInfoDao.selectByFtpFilePath(definitionFtpPath);
				if(ftpFileInfoEntity == null) {
					FtpFileInfoEntity record = new FtpFileInfoEntity();
					record.setCreatetime(new Date());
					record.setFtpfiledatetime("0");
					record.setFtpfilename(sftpUtil.getFileNamebyFtpPath(definitionFtpPath));
					record.setFtpfilepath(definitionFtpPath);
					record.setFtpfilesize(0L);
					record.setUpdatetime(record.getCreatetime());
					record.setFtpfilestatus(FtpFileStatusEnum.FTPFILE_STATUS_HANDLE.getCode());
					ftpFileInfoDao.insert(record);
					logger.info("保存的文件 -> {} ",record.toString());
				}
			}
		} catch (Exception e) {
			logger.error("保存优先下载的文件异常" + e.getMessage(),e);
			return R.error();
		}
		logger.info("保存优先下载的文件结束");
		return R.ok();
	}
	
	
	
	/**
	 * 下载在配置文件自定义的文件
	 * @param DefinitionFileNameList
	 * @param localPath
	 * @return
	 */
	public R downloadFtpFileByDefinition(List<String> DefinitionFileNameList,String localPath) {
		logger.info("下载自定义的文件开始：" + DefinitionFileNameList);
		ChannelSftp ftp = null;
		try {
			ftp = sftpUtil.getFTPConnection();
			
			for(String DefinitionFileName:DefinitionFileNameList) {
				Date beginTime = new Date();
				R r = sftpUtil.downloadFtpFileByFtpPath(DefinitionFileName,localPath,ftp);
				if(!R.checkOK(r)) {
					continue;
				}
				FTPFile ftpfile = (FTPFile) r.get("obj");
				Ftpfilelog ftpfilelogRecord = new Ftpfilelog();
				ftpfilelogRecord.setBegintime(beginTime);
				ftpfilelogRecord.setEndtime(new Date());
				long ftpfiledatetime = ftpfile.getTimestamp().getTimeInMillis();
				int rawOffset = 0;
				long ftpfiledatetimeTotal = ftpfiledatetime + rawOffset;
				ftpfilelogRecord.setFtpfiledatetime(String.valueOf(ftpfiledatetimeTotal));
				ftpfilelogRecord.setFtpfilename(ftpfile.getName());
				ftpfilelogRecord.setFtpfilepath(DefinitionFileName);
				ftpfilelogRecord.setFtpfilesize(ftpfile.getSize());
				ftpfilelogRecord.setFtplocalpath(localPath + DefinitionFileName);
				ftpfilelogRecord.setFtpfiletype(FileTypeEnum.DOWNLOAD.getCode());
				ftpfilelogDao.insert(ftpfilelogRecord);
			}
			return R.ok();
		}catch(Exception e){
			logger.error(e.getMessage(),e);	
			return R.error("下载自定义的文件失败");
		}finally {
			sftpUtil.closeSFTPConnection(ftp);
			logger.info("下载自定义的文件结束：" + DefinitionFileNameList);
		}
		
	}
	
	/**
	   * 下载指定DB中的文件,多线程
	   * 检测服务器文件是否正在处理 
	 * @param ftpPath
	 * @param localPath
	 */
	public R downloadFtpFileByDBAndThread(String ftpDirectory, String localPath,int n ) {
		logger.info("下载指定目录(DB)下的文件开始：" + ftpDirectory);
		try {
			//对数据库进行查询，查询状态为1的数据
			List<FtpFileInfoEntity> ftpFileInfoEntityList = ftpFileInfoDao.selectByFtpFileStatus(FtpFileStatusEnum.FTPFILE_STATUS_DOWNLOAD.getCode());
			List<List<FtpFileInfoEntity>> lists = ListUtil.averageAssign(ftpFileInfoEntityList, n);
			for(List<FtpFileInfoEntity> ftpfileInfoList : lists) {
				TransportThreadService tts = new TransportThreadService();
				tts.setFtpFileInfoEntityList(ftpfileInfoList);
				tts.setLocalPath(localPath);
				Thread t = new Thread(tts);
				t.start();
			}
			return R.ok();
		} catch (Exception e) {
			logger.error(e.getMessage(),e);	
			return R.error("下载指定目录(DB)的文件失败" + ftpDirectory);
		}finally {
		}
	}
	
	/**
	 * 上传指定的文件
	 * @param ftpDirectory
	 * @param localPath
	 * @return
	 */
	/*public R uploadFileByLocalPath(String ftpDirectory, String localPath) {
		ChannelSftp ftp = null;
		try {
			File localFile = new File(localPath);
			if(localFile.isFile()) {
				ftp = sftpUtil.getUpFTPConnection();
				Date beginTime = new Date();
				R r = sftpUtil.uploadFile(ftpDirectory, localPath, ftp);
				if(R.checkOK(r)) {
					Ftpfilelog ftpfilelogRecord = new Ftpfilelog();
					ftpfilelogRecord.setBegintime(beginTime);
					ftpfilelogRecord.setEndtime(new Date());
					ftpfilelogRecord.setFtpfiledatetime(String.valueOf(localFile.lastModified()));
					ftpfilelogRecord.setFtpfilename(localFile.getName());
					ftpfilelogRecord.setFtpfilepath(ftpDirectory);
					ftpfilelogRecord.setFtpfilesize(localFile.length());
					ftpfilelogRecord.setFtplocalpath(localFile.getPath());
					ftpfilelogRecord.setFtpfiletype(FileTypeEnum.UPLOAD.getCode());
					ftpfilelogDao.insert(ftpfilelogRecord);
				}
				return r;
			}else {
				logger.info("文件不存在" + localPath);
				return R.error("文件不存在");
			}
			
		} catch (Exception e) {
			return R.error();
		} finally {
			sftpUtil.closeSFTPConnection(ftp);
		}
		
	}*/
	
	public String makeSubDirecotry(String localPath,String localDirectory,String fileName) {
		if(File.separator.equals("\\")){
			localPath = localPath.replace("\\", "/");
		}
		String subLoaclPath = localPath.replace(localDirectory, "");
		if(subLoaclPath != null && !subLoaclPath.equals(fileName)) {
			subLoaclPath = subLoaclPath.replace(fileName, "");
			subLoaclPath = subLoaclPath.substring(0,subLoaclPath.length() -1) + "/" ;
			return subLoaclPath;
		}else {
			return "";
		}
	}
	
	
	/**
	 * 创建FPT目录，带日期
	 * @param fileType
	 * @return
	 */
	public String makeFtpDirectory(FileTypeEnum fileType) {
		String subDirectory = DateUtils.DateCount(ftpServerInfo.getDelayTime(), DateUtils.DATEPATTERN);
		String detailDirectory = "";
		if(FileTypeEnum.UPLOAD.getCode().equals(fileType.getCode())) {
			detailDirectory = ftpServerInfo.getFtpUploadDirectory()+subDirectory+ "/";
		}else {
			detailDirectory = ftpServerInfo.getFtpDirectory()+subDirectory+ "/";
		}
		return detailDirectory;
	}
	
	/**
	 * 创建本地保存文件目录
	 * 由固定目录+ftp目录+日期
	 * @return
	 */
	public String makeLocalFileDirectory() {
		String subDirectory = DateUtils.DateCount(ftpServerInfo.getDelayTime(), DateUtils.DATEPATTERN);
		String localFileDirectory = ftpServerInfo.getLocalDirectory().substring(0, ftpServerInfo.getLocalDirectory().length()-1)+ ftpServerInfo.getFtpDirectory() + subDirectory;
		return localFileDirectory;
	}
	
	/**
	 * 创建从配置文件获取文件的ftpPath
	 * 包括文件名称
	 * @return
	 */
	public List<String> makeFtpPathByDifiniton(){
		List<String> DefinitionFileNameList = ftpServerInfo.getDefinitionFileName();
		List<String> definitionFilePathList = new ArrayList<String>();
		for(String fileName : DefinitionFileNameList) {
			String ftpFilePath = makeFtpDirectory(FileTypeEnum.DOWNLOAD)+fileName;
			definitionFilePathList.add(ftpFilePath);
		}
		return definitionFilePathList;
	}
	
}
